import pandas as pd
from pyecharts.charts import Pie
from pyecharts import options as opts

# 数据文件地址
csv_file = "data\数据.csv"  # 替换为你的文件路径

# 读取 CSV 文件，使用制表符分隔
df = pd.read_csv(csv_file, sep="\t")

# 确保列名无空格或乱码
df.columns = df.columns.str.strip()

# 按分类统计总字数
category_word_count = (
    df.groupby("分类")["字数"]
    .sum()
    .reset_index()
    .rename(columns={"字数": "总字数"})
)

# 准备饼图数据
data_pair = [
    (row["分类"], row["总字数"]) for _, row in category_word_count.iterrows()
]

# 创建饼图
pie = (
    Pie()
    .add(
        series_name="分类总字数占比",
        data_pair=data_pair,
        radius=["30%", "70%"],  # 设置内外半径，形成环形饼图
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(title="各分类的总字数占比饼图"),
        legend_opts=opts.LegendOpts(pos_bottom="5%"),
    )
    .set_series_opts(
        label_opts=opts.LabelOpts(
            formatter="{b}: {d}%"  # 显示分类名称和占比
        )
    )
)

# 保存图表
output_file = "category_wordcount_pie.html"
pie.render(output_file)
print(f"图表已保存为 {output_file}，打开即可查看。")
